// 安全的肉鸽整合系统 - 不破坏原有功能的增强
class RoguelikeIntegrationSafe {
    constructor() {
        this.initialized = false;
        this.levelEnhancements = {};
        this.currentEnhancements = [];
        this.safeMode = true; // 安全模式，避免破坏原有功能
        
        // 关卡特定的肉鸽配置
        this.levelConfigs = this.initializeLevelConfigs();
        
        // 延迟初始化，确保所有系统加载完成
        setTimeout(() => {
            this.initialize();
        }, 3000); // 增加延迟时间
    }
    
    initialize() {
        if (this.initialized) return;
        
        try {
            console.log('🎮 开始安全初始化肉鸽整合系统...');
            
            // 检查系统可用性但不强制依赖
            this.checkSystemAvailability();
            
            // 设置非侵入式的增强
            this.setupNonIntrusiveEnhancements();
            
            // 设置事件监听器
            this.setupSafeEventListeners();
            
            this.initialized = true;
            console.log('✅ 肉鸽整合系统安全初始化完成');
            
        } catch (error) {
            console.error('肉鸽整合系统初始化失败:', error);
            console.log('🔄 切换到备用模式');
            this.fallbackMode();
        }
    }
    
    initializeLevelConfigs() {
        return {
            1: {
                name: '教学楼入口',
                equipmentDropRate: 0.3,
                description: '学习基本肉鸽机制'
            },
            2: {
                name: '学校走廊',
                equipmentDropRate: 0.4,
                description: '开始体验程序化内容'
            },
            3: {
                name: '图书馆惊魂',
                equipmentDropRate: 0.5,
                description: '引入环境交互和选择'
            },
            4: {
                name: '化学实验室',
                equipmentDropRate: 0.6,
                description: '风险与收益的平衡'
            },
            5: {
                name: '学校食堂',
                equipmentDropRate: 0.7,
                description: '中期挑战和策略选择'
            },
            6: {
                name: '体育馆血战',
                equipmentDropRate: 0.8,
                description: '技能考验和装备升级'
            },
            7: {
                name: '宿舍楼围困',
                equipmentDropRate: 0.9,
                description: '持续压力和资源管理'
            },
            8: {
                name: '天台最后防线',
                equipmentDropRate: 1.0,
                description: '高强度生存挑战'
            },
            9: {
                name: '地下室深渊',
                equipmentDropRate: 1.2,
                description: '极限挑战和心理压力'
            },
            10: {
                name: '校长室终极对决',
                equipmentDropRate: 1.5,
                description: '最终考验和荣耀时刻'
            }
        };
    }
    
    checkSystemAvailability() {
        const systems = {
            roguelikeSystem: window.roguelikeSystem,
            roguelikeEnhanced: window.roguelikeEnhanced,
            equipmentSystem: window.equipmentSystem,
            gameEngine: window.gameEngine,
            levelManager: window.levelManager
        };
        
        Object.entries(systems).forEach(([name, system]) => {
            if (system) {
                console.log(`✅ ${name} 系统可用`);
            } else {
                console.warn(`⚠️ ${name} 系统不可用`);
            }
        });
    }
    
    setupNonIntrusiveEnhancements() {
        // 不重写原有方法，而是使用事件监听和钩子
        this.setupLevelStartHooks();
        this.setupZombieDeathHooks();
        this.setupLevelCompleteHooks();
    }
    
    setupLevelStartHooks() {
        // 监听关卡开始，而不是重写方法
        const originalConsoleLog = console.log;
        let levelStartDetected = false;
        
        // 检测关卡开始的模式
        const checkLevelStart = () => {
            if (window.levelManager && window.levelManager.currentLevel && 
                window.gameEngine && window.gameEngine.gameState === 'playing' && 
                !levelStartDetected) {
                
                levelStartDetected = true;
                this.onLevelStart(window.levelManager.currentLevel);
                
                // 重置检测标志
                setTimeout(() => {
                    levelStartDetected = false;
                }, 5000);
            }
        };
        
        // 定期检查关卡状态
        setInterval(checkLevelStart, 1000);
    }
    
    onLevelStart(levelNumber) {
        console.log(`🎯 检测到关卡 ${levelNumber} 开始，应用肉鸽增强`);
        
        try {
            const config = this.levelConfigs[levelNumber];
            if (config) {
                this.enhanceLevelSafely(levelNumber, config);
            }
        } catch (error) {
            console.error('关卡增强失败:', error);
        }
    }
    
    enhanceLevelSafely(levelNumber, config) {
        // 安全地增强关卡，不破坏原有功能
        
        // 1. 显示关卡特色提示
        this.showLevelHint(config);
        
        // 2. 安排装备掉落
        this.scheduleEquipmentDropsSafely(levelNumber, config);
        
        // 3. 应用升级选择（关卡完成后）
        this.scheduleUpgradeSelection(levelNumber);
        
        // 4. 触发随机事件（延迟触发）
        this.scheduleRandomEvents(levelNumber);
    }
    
    scheduleEquipmentDropsSafely(levelNumber, config) {
        if (!window.equipmentSystem || !window.gameEngine) return;
        
        const dropCount = Math.min(3, Math.floor(1 + levelNumber * 0.2));
        
        for (let i = 0; i < dropCount; i++) {
            setTimeout(() => {
                try {
                    if (window.gameEngine && window.gameEngine.gameState === 'playing') {
                        const x = Math.random() * 800 + 100;
                        const y = Math.random() * 600 + 100;
                        
                        // 根据关卡调整稀有度
                        let rarity = 'common';
                        if (levelNumber >= 5) {
                            const rand = Math.random();
                            if (rand < 0.1) rarity = 'epic';
                            else if (rand < 0.3) rarity = 'rare';
                        } else if (levelNumber >= 3) {
                            if (Math.random() < 0.2) rarity = 'rare';
                        }
                        
                        window.equipmentSystem.spawnEquipmentDrop(x, y, null, rarity);
                        console.log(`📦 在关卡 ${levelNumber} 生成 ${rarity} 装备`);
                    }
                } catch (error) {
                    console.error('装备掉落失败:', error);
                }
            }, Math.random() * 30000 + 10000); // 10-40秒内随机掉落
        }
    }
    
    scheduleUpgradeSelection(levelNumber) {
        // 监听关卡完成状态
        const checkLevelComplete = () => {
            if (window.gameEngine && window.gameEngine.gameState === 'levelComplete') {
                setTimeout(() => {
                    if (window.roguelikeSystem && typeof window.roguelikeSystem.showUpgradeSelection === 'function') {
                        try {
                            window.roguelikeSystem.showUpgradeSelection();
                            console.log(`🎲 关卡 ${levelNumber} 完成，显示升级选择`);
                        } catch (error) {
                            console.error('升级选择显示失败:', error);
                        }
                    }
                }, 2000);
                return true; // 停止检查
            }
            return false;
        };
        
        // 检查关卡完成状态
        const checkInterval = setInterval(() => {
            if (checkLevelComplete()) {
                clearInterval(checkInterval);
            }
        }, 1000);
        
        // 60秒后停止检查
        setTimeout(() => {
            clearInterval(checkInterval);
        }, 60000);
    }
    
    scheduleRandomEvents(levelNumber) {
        if (levelNumber < 3) return; // 前两关不触发随机事件
        
        setTimeout(() => {
            if (window.gameEngine && window.gameEngine.gameState === 'playing' && 
                window.roguelikeEnhanced && window.roguelikeEnhanced.eventSystem) {
                
                try {
                    const event = window.roguelikeEnhanced.eventSystem.generateRandomEvent();
                    if (event && window.roguelikeEnhanced.showEventInterface) {
                        window.roguelikeEnhanced.showEventInterface(event);
                        console.log(`🎪 关卡 ${levelNumber} 触发随机事件: ${event.title}`);
                    }
                } catch (error) {
                    console.error('随机事件触发失败:', error);
                }
            }
        }, Math.random() * 25000 + 15000); // 15-40秒后触发
    }
    
    setupZombieDeathHooks() {
        // 不重写zombie.die方法，而是定期检查僵尸击杀数
        let lastKillCount = 0;
        
        setInterval(() => {
            if (window.storageManager) {
                try {
                    const currentData = window.storageManager.loadData();
                    const currentKills = currentData.player?.totalKills || 0;
                    
                    if (currentKills > lastKillCount) {
                        const newKills = currentKills - lastKillCount;
                        this.onZombieKilled(newKills);
                        lastKillCount = currentKills;
                    }
                } catch (error) {
                    // 静默处理错误
                }
            }
        }, 2000);
    }
    
    onZombieKilled(killCount) {
        // 随机掉落奖励
        for (let i = 0; i < killCount; i++) {
            if (Math.random() < 0.1 && window.equipmentSystem && window.gameEngine) { // 10%概率掉落
                try {
                    const x = Math.random() * 800 + 100;
                    const y = Math.random() * 600 + 100;
                    window.equipmentSystem.spawnEquipmentDrop(x, y, 'item', 'common');
                } catch (error) {
                    console.error('击杀奖励掉落失败:', error);
                }
            }
        }
        
        // 更新统计
        if (window.roguelikeEnhanced) {
            try {
                window.roguelikeEnhanced.updateRunStats(killCount, 0);
            } catch (error) {
                console.error('统计更新失败:', error);
            }
        }
    }
    
    setupLevelCompleteHooks() {
        // 监听关卡完成
        let lastLevel = 0;
        
        setInterval(() => {
            if (window.levelManager && window.levelManager.currentLevel > lastLevel) {
                this.onLevelComplete(window.levelManager.currentLevel);
                lastLevel = window.levelManager.currentLevel;
            }
        }, 2000);
    }
    
    onLevelComplete(levelNumber) {
        console.log(`🏆 关卡 ${levelNumber} 完成`);
        
        // 奖励金币
        if (window.roguelikeSystem) {
            try {
                const coinReward = 20 + levelNumber * 5;
                window.roguelikeSystem.addCurrency(coinReward);
                console.log(`💰 获得 ${coinReward} 金币奖励`);
            } catch (error) {
                console.error('金币奖励失败:', error);
            }
        }
        
        // 更新运行统计
        if (window.roguelikeEnhanced) {
            try {
                window.roguelikeEnhanced.completeLevel(levelNumber);
            } catch (error) {
                console.error('关卡完成统计失败:', error);
            }
        }
    }
    
    setupSafeEventListeners() {
        // 设置安全的事件监听器
        document.addEventListener('keydown', (e) => {
            if (e.code === 'KeyP' && e.ctrlKey) {
                this.toggleDebugInfo();
            }
        });
    }
    
    toggleDebugInfo() {
        console.log('🎮 肉鸽系统状态:');
        console.log('- 初始化状态:', this.initialized);
        console.log('- 当前关卡:', window.levelManager?.currentLevel);
        console.log('- 游戏状态:', window.gameEngine?.gameState);
        console.log('- 可用系统:', {
            roguelikeSystem: !!window.roguelikeSystem,
            equipmentSystem: !!window.equipmentSystem,
            roguelikeEnhanced: !!window.roguelikeEnhanced
        });
    }
    
    showLevelHint(config) {
        if (!config) return;
        
        try {
            this.showNotification(
                `🎯 ${config.name}`,
                config.description,
                '#2196F3',
                4000
            );
        } catch (error) {
            console.error('关卡提示显示失败:', error);
        }
    }
    
    showNotification(title, message, color = '#4CAF50', duration = 3000) {
        try {
            const notification = document.createElement('div');
            notification.className = 'safe-roguelike-notification';
            notification.style.cssText = `
                position: fixed;
                top: 20px;
                right: 20px;
                z-index: 10000;
                background: linear-gradient(135deg, rgba(0, 0, 0, 0.9), rgba(30, 30, 30, 0.9));
                border: 2px solid ${color};
                border-radius: 12px;
                padding: 15px 20px;
                color: white;
                max-width: 300px;
                box-shadow: 0 5px 20px rgba(0, 0, 0, 0.3);
                animation: slideInFromRight 0.5s ease-out;
            `;
            
            notification.innerHTML = `
                <h4 style="margin: 0 0 8px 0; color: ${color}; font-size: 16px;">${title}</h4>
                <p style="margin: 0; font-size: 14px; opacity: 0.9;">${message}</p>
            `;
            
            document.body.appendChild(notification);
            
            // 添加动画样式
            this.addNotificationStyles();
            
            // 自动移除
            setTimeout(() => {
                if (notification.parentNode) {
                    notification.style.animation = 'slideOutToRight 0.5s ease-in';
                    setTimeout(() => {
                        if (notification.parentNode) {
                            document.body.removeChild(notification);
                        }
                    }, 500);
                }
            }, duration);
            
        } catch (error) {
            console.error('通知显示失败:', error);
        }
    }
    
    addNotificationStyles() {
        if (document.getElementById('safeRoguelikeNotificationStyles')) return;
        
        const styles = document.createElement('style');
        styles.id = 'safeRoguelikeNotificationStyles';
        styles.textContent = `
            @keyframes slideInFromRight {
                0% { opacity: 0; transform: translateX(100px); }
                100% { opacity: 1; transform: translateX(0); }
            }
            
            @keyframes slideOutToRight {
                0% { opacity: 1; transform: translateX(0); }
                100% { opacity: 0; transform: translateX(100px); }
            }
        `;
        
        document.head.appendChild(styles);
    }
    
    fallbackMode() {
        // 备用模式，提供最基本的功能
        console.log('🔄 启动备用模式');
        
        // 简化的关卡提示
        setInterval(() => {
            if (window.levelManager && window.levelManager.currentLevel) {
                const config = this.levelConfigs[window.levelManager.currentLevel];
                if (config && Math.random() < 0.1) { // 10%概率显示提示
                    console.log(`💡 关卡提示: ${config.description}`);
                }
            }
        }, 10000);
    }
}

// 替换原有的整合系统
if (window.roguelikeIntegration) {
    delete window.roguelikeIntegration;
}

window.roguelikeIntegrationSafe = new RoguelikeIntegrationSafe();

console.log('🛡️ 安全肉鸽整合系统已加载');